<template>
  <div class="notice-container">
    <div class="header">
      <div class="flex justify-between items-center mb-4">
        <h1 class="title">系统公告</h1>
        <el-button 
          type="primary" 
          @click="handleCreate"
          class="add-btn">
          <el-icon><Plus /></el-icon>
          新增公告
        </el-button>
      </div>
      <el-divider class="title-divider" />
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar mb-4">
      <el-popconfirm 
        title="确认删除选中公告吗？" 
        @confirm="handleBatchDelete"
        :disabled="selectedIds.length === 0">
        <template #reference>
          <el-button 
            :disabled="selectedIds.length === 0"
            type="danger" 
            plain>
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </template>
      </el-popconfirm>
    </div>

    <!-- 公告列表 -->
    <el-skeleton :loading="loading" animated :count="3">
      <template #template>
        <div class="skeleton-item">
          <el-skeleton-item variant="h3" style="width: 200px" />
          <el-skeleton-item variant="text" style="width: 80%" />
          <div class="skeleton-footer">
            <el-skeleton-item variant="text" style="width: 120px" />
          </div>
        </div>
      </template>

      <template #default>
        <transition-group name="list" tag="div">
          <el-card 
            v-for="notice in notices" 
            :key="notice.noticeId"
            class="notice-card"
            shadow="never"
          >
            <div class="card-header">
              <div class="notice-type">
                <el-checkbox 
                  v-model="selectedIds" 
                  :label="notice.noticeId"
                  class="mr-3" />
                <el-tag 
                  :type="typeStyle[notice.type]"
                  class="type-tag"
                  effect="plain"
                >
                  {{ typeMap[notice.type] || '其他公告' }}
                </el-tag>
                <div class="time-info">
                  <el-icon class="time-icon"><Clock /></el-icon>
                  <span class="time-text">{{ formatTime(notice.createdAt) }}</span>
                </div>
              </div>
              <div class="action-btns">
                <el-button 
                  type="primary" 
                  link
                  @click="handleEdit(notice)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-popconfirm 
                  title="确认删除该公告吗？" 
                  @confirm="handleDelete(notice.noticeId)">
                  <template #reference>
                    <el-button type="danger" link>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>

            <h3 class="notice-content">
              {{ notice.content }}
            </h3>

            <div class="update-time">
              <el-text type="info" size="small">
                最后更新：{{ formatTime(notice.updatedAt) }}
              </el-text>
            </div>
          </el-card>
        </transition-group>
      </template>
    </el-skeleton>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.noticeId ? '编辑公告' : '新增公告'"
      width="600px">
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="rules"
        label-width="80px">
        <el-form-item label="公告类型" prop="type">
          <el-select 
            v-model="form.type" 
            placeholder="请选择类型"
            class="w-full">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="5"
            placeholder="请输入公告内容"
            maxlength="500"
            show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-empty 
      v-if="!loading && notices.length === 0" 
      description="暂无公告"
      class="empty-box" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { 
  Clock, Plus, Delete, Edit 
} from '@element-plus/icons-vue'

// 公告数据
const loading = ref(true)
const notices = ref([])
const selectedIds = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const formRef = ref(null)
const form = reactive({
  noticeId: null,
  type: 1,
  content: ''
})

// 验证规则
const rules = reactive({
  type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 10, message: '内容不能少于10个字符', trigger: 'blur' }
  ]
})

// 类型配置
const typeMap = {
  1: '📢 系统公告',
  2: '🎉 活动通知',
  3: '🔧 维护公告'
}

const typeStyle = {
  1: '',
  2: 'success',
  3: 'warning'
}

const typeOptions = [
  { value: 1, label: '系统公告' },
  { value: 2, label: '活动通知' },
  { value: 3, label: '维护公告' }
]

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY/MM/DD HH:mm')
}

// 获取公告列表
const fetchNotices = async () => {
  try {
    const res = await axios.get('http://localhost:8092/notice/list')
    notices.value = res.data.data
  } catch (error) {
    ElMessage.error('公告加载失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 打开创建弹窗
const handleCreate = () => {
  form.noticeId = null
  form.type = 1
  form.content = ''
  dialogVisible.value = true
}

// 打开编辑弹窗
const handleEdit = (notice) => {
  form.noticeId = notice.noticeId
  form.type = notice.type
  form.content = notice.content
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    const api = form.noticeId 
      ? axios.put('http://localhost:8092/notice', form)
      : axios.post('http://localhost:8092/notice', form)

    const res = await api
    if (res.data.code === 200) {
      ElMessage.success(form.noticeId ? '更新成功' : '创建成功')
      dialogVisible.value = false
      fetchNotices()
    }
  } catch (error) {
    ElMessage.error('操作失败：' + error.message)
  }
}

// 删除公告
const handleDelete = async (id) => {
  try {
    await axios.delete(`http://localhost:8092/notice/${id}`)
    ElMessage.success('删除成功')
    fetchNotices()
  } catch (error) {
    ElMessage.error('删除失败：' + error.message)
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await axios.post('http://localhost:8092/notice/batchDelete', selectedIds.value)
    ElMessage.success(`已删除 ${selectedIds.value.length} 条公告`)
    selectedIds.value = []
    fetchNotices()
  } catch (error) {
    ElMessage.error('批量删除失败：' + error.message)
  }
}

onMounted(fetchNotices)
</script>

<style scoped>
.notice-container {
  max-width: 1200px;
  margin: 40px auto;
  padding: 0 24px;
}

.header {
  margin-bottom: 32px;
}

.title {
  font-size: 24px;
  color: #2c3e50;
  letter-spacing: 2px;
}

.title-divider {
  margin: 16px 0;
  background: #409EFF;
}

.notice-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: 1px solid #ebeef5;
  transition: box-shadow 0.3s;
}

.notice-card:hover {
  box-shadow: 0 6px 16px -4px rgba(0,0,0,0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.type-tag {
  border-radius: 4px;
  font-weight: 500;
  padding: 4px 8px;
  margin-right: 12px;
}

.time-info {
  display: flex;
  align-items: center;
  color: #909399;
}

.time-icon {
  margin-right: 6px;
  font-size: 14px;
}

.time-text {
  font-size: 13px;
}

.notice-content {
  margin: 16px 0;
  font-size: 16px;
  line-height: 1.6;
  color: #303133;
  font-weight: 400;
}

.update-time {
  text-align: right;
  font-size: 12px;
  color: #909399;
}

.skeleton-item {
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  background: #fff;
}

.empty-box {
  padding: 60px 0;
}

.action-btns {
  display: flex;
  gap: 12px;
}

.add-btn {
  margin-left: auto;
}

.operation-bar {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

@media (max-width: 768px) {
  .notice-container {
    padding: 0 16px;
  }
  
  .title {
    font-size: 20px;
  }
  
  .notice-content {
    font-size: 15px;
  }

  .action-btns {
    flex-direction: column;
    gap: 8px;
  }
}
</style>